<template>
  <div>
    <div v-for="(category, index) in categoryTree" :key="'cat-' + category.id">
      <div class="i_t mar_10">
        <span class="floor_num">{{ index + 1 }}F</span>
        <span class="fl" @click="goToSearchProduct(1, category.id)">
          {{ category.name }}</span
        >

        <span
          class="i_mores fr"
          v-for="subCategory in category.children || []"
          :key="'sub-' + subCategory.id"
        >
          <!-- 二级分类标题 -->
          <a @click="goToSearchProduct(2, subCategory.id)">
            {{ subCategory.name }} </a
          >&nbsp;&nbsp;&nbsp;
        </span>
      </div>

      <div class="content">
        <div class="fresh_left">
          <div class="fre_ban">
            <div id="imgPlay1">
              <ul class="imgs" id="actor1">
                <li>
                  <a href="#">
                    <img
                      :src="require('@/assets/images/fre_r.jpg')"
                      width="211"
                      height="286"
                    />
                  </a>
                </li>
              </ul>
              <div class="prevf">上一张</div>
              <div class="nextf">下一张</div>
            </div>
          </div>
          <div class="fresh_txt">
            <div class="fresh_txt_c">
              <template v-for="subCategory in category.children || []">
                <a
                  v-for="subSubCategory in subCategory.children || []"
                  :key="'subsub-' + subSubCategory.id"
                  @click="goToSearchProduct(3, subSubCategory.id)"
                >
                  {{ subSubCategory.name }}&nbsp;&nbsp;
                </a>
              </template>
            </div>
          </div>
        </div>
        <div class="fresh_mid">
          <ul>
            <!-- 动态渲染产品列表 -->
            <li
              v-for="product in category.products || []"
              :key="'prod-' + product.id"
            >
              <div class="name">
                <a @click="goToProductDetail(product.id)">{{
                  product.productName
                }}</a>
              </div>
              <div class="price">
                <font
                  >￥<span>{{ product.price }}</span></font
                >
                &nbsp;
              </div>
              <div class="img">
                <a @click="goToProductDetail(product.id)">
                  <img
                    :src="`http://117.72.153.227/image/${
                      product.fileName || ''
                    }`"
                    width="185"
                    height="155"
                  />
                </a>
              </div>
            </li>
          </ul>
        </div>
        <div class="fresh_right">
          <ul>
            <li>
              <a href="#"
                ><img
                  :src="require('@/assets/images/fre_b1.jpg')"
                  width="260"
                  height="220"
              /></a>
            </li>
            <li>
              <a href="#"
                ><img
                  :src="require('@/assets/images/fre_b2.jpg')"
                  width="260"
                  height="220"
              /></a>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: "FloorProducts",
  data() {
    return {
      categoryTree: [],
    };
  },
  computed: {
    currentCategory() {
      return this.categoryTree.find((c) => c.id) || null;
    },
  },
  async created() {
    try {
      await this.fetchCategoryTree(); // 等待分类加载完成
      await this.fetchProductsForCategories(); // 再加载产品
    } catch (error) {
      console.error("初始化数据失败:", error);
    }
  },
  methods: {
    async fetchCategoryTree() {
      try {
        const res = await axios.get("/api/category/getCategoryTree");
        this.categoryTree = (res.data.categoryTree || []).map((category) => ({
          ...category,
          children: category.children || [],
          products: [], // 初始化产品数组
        }));
      } catch (error) {
        console.error("获取分类数据失败:", error);
      }
    },
    goToSearchProduct(levelId, categoryId) {
      const query = {};
      let categoryPath = [];

      switch (levelId) {
        case 1: {
          const category1 = this.categoryTree.find((c) => c.id === categoryId);
          if (category1) {
            categoryPath = [category1.name];
          }
          query.categoryId = categoryId;
          break;
        }

        case 2: {
          for (const cat1 of this.categoryTree) {
            const cat2 = cat1.children?.find((c) => c.id === categoryId);
            if (cat2) {
              categoryPath = [cat1.name, cat2.name];
              break;
            }
          }
          query.subCategoryId = categoryId;
          break;
        }

        case 3: {
          for (const cat1 of this.categoryTree) {
            for (const cat2 of cat1.children || []) {
              const cat3 = cat2.children?.find((c) => c.id === categoryId);
              if (cat3) {
                categoryPath = [cat1.name, cat2.name, cat3.name];
                break;
              }
            }
          }
          query.thirdCategoryId = categoryId;
          break;
        }
      }
      this.$router.push({
        path: "/SearchProduct",
        query: {
          ...query,
          page: 1,
          categoryPath: JSON.stringify(categoryPath),
        },
      });
    },
    async fetchProductsForCategories() {
      try {
        if (!this.categoryTree.length) {
          console.warn("分类数据为空，无法加载产品");
          return;
        }

        const requests = this.categoryTree.map((category) =>
          axios.get("/api/product/searchProduct", {
            params: {
              pageNum: 1,
              pageSize: 6,
              categoryLevel1Id: category.id, // 确保参数名与后端一致
            },
          })
        );

        const responses = await Promise.all(requests);
        responses.forEach((res, index) => {
          const category = this.categoryTree[index];
          // console.log(`分类 ${category.id} 响应:`, res.data);

          // 严格校验数据层级
          if (res.data?.code === 200 && res.data?.pageInfo?.list) {
            const products = res.data.pageInfo.list;
            if (Array.isArray(products) && products.length > 0) {
              this.$set(category, "products", products); // 正确绑定产品数据
            } else {
              console.warn(`分类 ${category.id} 产品列表为空`);
              this.$set(category, "products", []);
            }
          } else {
            console.error(
              `分类 ${category.id} 接口异常:`,
              res.data?.msg || "未知错误"
            );
            this.$set(category, "products", []);
          }
        });
      } catch (error) {
        console.error("产品请求失败:", error);
      }
    },
    goToProductDetail(productId) {
      this.$router.push(`/ShowProduct/${productId}`);
    },
  },
};
</script>

<style>
.fresh_mid ul {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.fresh_mid ul li {
  width: 32%;
  margin-bottom: 20px;
}

/* 保持图片比例 */
.fresh_mid ul li img {
  object-fit: cover;
  height: 155px;
}
</style>